//
//  KPBaseTabbarViewController.swift
//  KPBaseProject
//
//  Created by Kipp Dev on 2018/3/21.
//  Copyright © 2018年 Kipp. All rights reserved.
//

import UIKit
import ESTabBarController_swift

class KPBaseTabbarViewController: ESTabBarController, UITabBarControllerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        prepareView()
        // Do any additional setup after loading the view.
    }

    override var preferredStatusBarStyle: UIStatusBarStyle {
        return selectedViewController!.preferredStatusBarStyle
    }

    override var childViewControllerForStatusBarStyle: UIViewController? {
        return super.childViewControllerForStatusBarStyle
    }
    override func setNeedsStatusBarAppearanceUpdate() {
        super.setNeedsStatusBarAppearanceUpdate()
    }

    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        /*
         需要登录的item将这个打开
         if isLogin.value == false {
         if viewController != self.viewControllers![0] && viewController != self.viewControllers![4] {
         let al = UIAlertController.init(title: "提示", message: "请登陆", preferredStyle: .alert)
         let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
         let okAction = UIAlertAction(title: "确定", style: .default, handler:{(sender) in
         NotificationCenter.default.post(name: NSNotification.Name(rawValue: "pushLogin"), object: nil)
         })
         al.addAction(cancelAction)
         al.addAction(okAction)
         self.present(al, animated: true, completion: nil)
         return false
         }else{
         return true
         }
         }
         */
        return true
    }

    // MARK: - 创建视图
    fileprivate func prepareView() {
        tabBar.shadowImage = UIImage()

        // MARK: - 用于指定中间有自定义按钮时的点击事件
        shouldHijackHandler = {tabbar,vc,index in
            return index == 2
        }

        didHijackHandler = { tabbar,vc,index in
            KPLog("中间按钮！")
        }

        let home = KPFirstViewController()
        let message = KPSecondViewController()
        let new = KPBaseViewController()
        let order = KPThirdViewController()
        let mine = KPFourViewController()
        home.tabBarItem = ESTabBarItem.init(KPTabBarItemContentView(),title: "首页", image: #imageLiteral(resourceName: "首页2"), selectedImage: #imageLiteral(resourceName: "首页"), tag: 100)
        message.tabBarItem = ESTabBarItem.init(KPTabBarItemContentView(),title: "消息", image: #imageLiteral(resourceName: "消息1"), selectedImage: #imageLiteral(resourceName: "消息2"), tag: 101)
        new.tabBarItem = ESTabBarItem.init(KPIrregularityContentView(),title: "发布", image: #imageLiteral(resourceName: "我要发布"), selectedImage: #imageLiteral(resourceName: "我要发布"), tag: 102)
        order.tabBarItem = ESTabBarItem.init(KPTabBarItemContentView(),title: "功能列表", image: #imageLiteral(resourceName: "钱包"), selectedImage: #imageLiteral(resourceName: "钱包2"), tag: 103)
        mine.tabBarItem = ESTabBarItem.init(KPTabBarItemContentView(),title: "我的", image: #imageLiteral(resourceName: "我的1"), selectedImage: #imageLiteral(resourceName: "我的2"), tag: 104)

        let n1 = KPBaseNavigationViewController(rootViewController: home)
        let n2 = KPBaseNavigationViewController(rootViewController: message)
        let n3 = KPBaseNavigationViewController(rootViewController: order)
        let n4 = KPBaseNavigationViewController(rootViewController: mine)

        setConfig(viewContros: [home,message,order,mine], titles: ["首页","消息","功能列表","我的"])
        viewControllers = [n1,n2,new,n3,n4]

    }

    func setConfig(viewContros:[UIViewController],titles:[String]) {
        for (index,item) in viewContros.enumerated() {
            item.title = titles[index]
            item.view.backgroundColor = UIColor.white//需要先调一次背景色，让ViewController先走viewdidload
            item.hidesBottomBarWhenPushed = false
        }
    }

}

// MARK: - 自定义 tabbaritem 样式
class KPTabBarItemContentView: ESTabBarItemContentView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        renderingMode = .alwaysOriginal
        textColor = #colorLiteral(red: 0.6745098039, green: 0.6745098039, blue: 0.6745098039, alpha: 1)
        highlightTextColor = #colorLiteral(red: 1, green: 0.337254902, blue: 0.1843137255, alpha: 1)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

// MARK: - 点击动画
class KPIrregularityContentView: ESTabBarItemContentView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        renderingMode = .alwaysOriginal
        self.imageView.layer.cornerRadius = imageView.frame.height/2
        self.insets = UIEdgeInsets(top: -32, left: 0, bottom: 0, right: 0)
        let transform = CGAffineTransform.identity
        self.imageView.transform = transform
        self.superview?.bringSubview(toFront: self)
        textColor = #colorLiteral(red: 0.6745098039, green: 0.6745098039, blue: 0.6745098039, alpha: 1)
        highlightTextColor = #colorLiteral(red: 0.6745098039, green: 0.6745098039, blue: 0.6745098039, alpha: 1)

        backdropColor = .clear
        highlightBackdropColor = .clear

    }

    public required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        let p = CGPoint.init(x: point.x - imageView.frame.origin.x, y: point.y - imageView.frame.origin.y)
        return sqrt(pow(imageView.bounds.size.width / 2.0 - p.x, 2) + pow(imageView.bounds.size.height / 2.0 - p.y, 2)) < imageView.bounds.size.width / 2.0
    }

    override func updateLayout() {
        super.updateLayout()
        self.imageView.sizeToFit()
        self.imageView.center = CGPoint.init(x: self.bounds.size.width / 2.0, y: self.bounds.size.height / 2.0)
    }

    public override func selectAnimation(animated: Bool, completion: (() -> Void)?) {
        //        let view = UIView.init(frame: CGRect.init(origin: CGPoint.zero, size: CGSize(width: 2.0, height: 2.0)))
        //        view.layer.cornerRadius = 1.0
        //        view.layer.opacity = 0.5
        //
        //        view.backgroundColor = #colorLiteral(red: 1, green: 0.337254902, blue: 0.1843137255, alpha: 1)
        //        self.addSubview(view)
        //        playMaskAnimation(animateView: view, target: self.imageView, completion: {
        //            [weak view] in
        //            view?.removeFromSuperview()
        //            completion?()
        //        })
    }

    public override func reselectAnimation(animated: Bool, completion: (() -> Void)?) {
        completion?()
    }

    public override func deselectAnimation(animated: Bool, completion: (() -> Void)?) {
        completion?()
    }

    public override func highlightAnimation(animated: Bool, completion: (() -> Void)?) {
        UIView.beginAnimations("small", context: nil)
        UIView.setAnimationDuration(0.2)
        let transform = self.imageView.transform.scaledBy(x: 0.8, y: 0.8)
        self.imageView.transform = transform
        UIView.commitAnimations()
        completion?()
    }

    public override func dehighlightAnimation(animated: Bool, completion: (() -> Void)?) {
        UIView.beginAnimations("big", context: nil)
        UIView.setAnimationDuration(0.2)
        let transform = CGAffineTransform.identity
        self.imageView.transform = transform
        UIView.commitAnimations()
        completion?()
    }

    private func playMaskAnimation(animateView view: UIView, target: UIView, completion: (() -> Void)?) {
        view.center = CGPoint.init(x: target.frame.origin.x + target.frame.size.width / 2.0, y: target.frame.origin.y + target.frame.size.height / 2.0)

        //        let scale = POPBasicAnimation.init(propertyNamed: kPOPLayerScaleXY)
        //        scale?.fromValue = NSValue.init(cgSize: CGSize.init(width: 1.0, height: 1.0))
        //        scale?.toValue = NSValue.init(cgSize: CGSize.init(width: 36.0, height: 36.0))
        //        scale?.beginTime = CACurrentMediaTime()
        //        scale?.duration = 0.3
        //        scale?.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseOut)
        //        scale?.removedOnCompletion = true
        //
        //        let alpha = POPBasicAnimation.init(propertyNamed: kPOPLayerOpacity)
        //        alpha?.fromValue = 0.6
        //        alpha?.toValue = 0.6
        //        alpha?.beginTime = CACurrentMediaTime()
        //        alpha?.duration = 0.25
        //        alpha?.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseOut)
        //        alpha?.removedOnCompletion = true
        //
        //        view.layer.pop_add(scale, forKey: "scale")
        //        view.layer.pop_add(alpha, forKey: "alpha")
        //
        //        scale?.completionBlock = ({ animation, finished in
        //            completion?()
        //        })
    }

}
